//
//  PersonalTabBarController.m
//  Btpin
//
//  Created by Vic on 2019/3/12.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "PersonalTabBarController.h"
#import "PersonalHomeViewController.h"
#import "CompanyViewController.h"
#import "PFindViewController.h"
#import "PersonalMessageViewController.h"
#import "PersonalMineViewController.h"
#import "AppDelegate.h"

@interface PersonalTabBarController ()<UITabBarControllerDelegate>
/** 记录上一次被点击按钮的tag */
@property (nonatomic, assign) NSInteger previousClickedTag;
@property (nonatomic, strong) NSMutableArray *chatListArr;
@property (nonatomic, assign) NSInteger unReadCount;
@end

@implementation PersonalTabBarController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.delegate = self;
    self.view.backgroundColor = COLOR_OF_WHITE;
    
    NSString *role = UD_GetOForK(isUserRole);
    if (role && role.length && [role isEqualToString:@"2"]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(unreadCountForIM) name:NotificationFor_Msg_UnReadCount object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(unreadCountForIM) name:@"TUIKitNotification_TIMMessageListener" object:nil];
    }
    
    self.previousClickedTag = 0;
    self.unReadCount = 0;
    
    [self createViewControllers];
}
- (void)createViewControllers {
    PersonalHomeViewController *PHVC = [[PersonalHomeViewController alloc] init];
    PHVC.navigationItem.title = @"职位";
    RootNavigationController *NavPHVC = [[RootNavigationController alloc] initWithRootViewController:PHVC];
    
    CompanyViewController *CVC = [[CompanyViewController alloc] init];
    CVC.navigationItem.title = @"公司";
    RootNavigationController *NavCVC = [[RootNavigationController alloc] initWithRootViewController:CVC];
    
    PFindViewController *FVC = [[PFindViewController alloc] init];
    FVC.navigationItem.title = @"新闻";
    RootNavigationController *NavFVC = [[RootNavigationController alloc] initWithRootViewController:FVC];
    
    PersonalMessageViewController *PMeVC = [[PersonalMessageViewController alloc] init];
    PMeVC.navigationItem.title = @"消息";
    RootNavigationController *NavPMeVC = [[RootNavigationController alloc] initWithRootViewController:PMeVC];
    
    PersonalMineViewController *PMVC = [[PersonalMineViewController alloc] init];
    PMVC.navigationItem.title = @"我的";
    RootNavigationController *NavMVC = [[RootNavigationController alloc] initWithRootViewController:PMVC];
    
    self.viewControllers = @[NavPHVC, NavCVC, NavFVC, NavPMeVC, NavMVC];
    NSArray *selectImageNameArray = @[@"home_s", @"corj_s", @"find_s", @"message_s", @"mine_s"];
    NSArray *unSelectImageNameArray = @[@"home_n", @"corj_n", @"find_n", @"message_n", @"mine_n"];
    NSArray *titleArray = @[@"职位", @"公司", @"发现", @"消息", @"我的"];
    
    NSArray *items = self.tabBar.items;
    for (NSInteger i = 0; i < items.count; i++) {
        UITabBarItem *item = items[i];
        UIImage *unSelectImage = [UIImage imageNamed:unSelectImageNameArray[i]];
        unSelectImage = [unSelectImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *selectImage = [UIImage imageNamed:selectImageNameArray[i]];
        selectImage = [selectImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item = [item initWithTitle:titleArray[i] image:unSelectImage selectedImage:selectImage];
    }
    
    UIImage *img = [UIToolsControl getCustomImageWithRect:CGRectMake(0, 0, WIDTH, 0.5) color:COLOR_OF_WHITE];
    [self.tabBar setBackgroundImage:img];
    UIImage *imgShadow = [UIToolsControl getCustomImageWithRect:CGRectMake(0, 0, WIDTH, 0.5) color:THEMECOLOR_OF_TEXT_cccccc];
    [self.tabBar setShadowImage:imgShadow];
    
    NSString *role = UD_GetOForK(isUserRole);
    if (role && role.length && [role isEqualToString:@"2"]) {
        [self unreadCountForIM];
    }
    
    self.tabBar.tintColor = THEMECOLOR_OF_ORANGE;
}
- (BOOL)tabBarController:(UITabBarController*)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    [self unreadCountForIM];
    
    NSLog(@"viewcontoller===%@", viewController.childViewControllers);
    if ((viewController == [self.viewControllers lastObject]) || (viewController == self.viewControllers[3])) { // 打开登录界面
        if (Signin) {
            return YES;
        } else {
            [SharedApp showViewController:TabBarTypeOfSignin];
            
//            [UIToolsControl presentSignin:self callBack:^(BOOL signinFlag) {
//                if (signinFlag) {
//
//                }
//            }];
        }
        return NO;
    }
    return YES;
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if (viewController == self.viewControllers[3]) {
        self.viewControllers[3].tabBarItem.badgeValue = nil;
    }
    
    switch (tabBarController.selectedIndex) {
        case 0: {
            if (self.previousClickedTag == tabBarController.selectedIndex) { // 进行了第二次点击
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForPersonalJobRefresh object:nil];
            }
        } break;
        case 1: {
            if (self.previousClickedTag == tabBarController.selectedIndex) { // 进行了第二次点击
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForPersonalCompanyRefresh object:nil];
            }
        } break;
        case 2: {
            
        } break;
        case 3: {
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForPersonalReexamineRefresh object:nil];
        } break;
        case 4: {
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForPersonalMineBaseDataRefresh object:nil];
        } break;
        default:
            break;
    }
    
    self.previousClickedTag = tabBarController.selectedIndex;//记录上一次按钮的点击
}
- (void)unreadCountForIM {
    if ([[TIMManager sharedInstance] getLoginStatus] != TIM_STATUS_LOGINED) {
        return;
    }
    
    self.unReadCount = 0;
    TIMManager *manager = [TIMManager sharedInstance];
    self.chatListArr = [NSMutableArray arrayWithCapacity:0];
    NSArray *convs = [manager getConversationList];
    [self.chatListArr addObjectsFromArray:convs];
    
    __weak __typeof(self)weakSelf = self;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (TIMConversation *conv in convs) {
        if ([conv getType] == TIM_SYSTEM) {
            continue;
        }
        [arr addObject:[NSString stringWithFormat:@"%@", [conv getReceiver]]];
    }
    [[TIMFriendshipManager sharedInstance] getUsersProfile:arr forceUpdate:YES succ:^(NSArray<TIMUserProfile *> *profiles) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        for (TIMUserProfile *profile in profiles) {
            NSLog(@"user=%@", profile);
            NSMutableArray *listArr = [NSMutableArray arrayWithCapacity:0];
            if (profile.role == 1) {
                for (TIMConversation *tempConv in strongSelf.chatListArr) {
                    if ([[tempConv getReceiver] isEqualToString:profile.identifier]) {
                        [listArr addObject:tempConv];
                    }
                }
            }
            if (listArr&&listArr.count) {
                for (TIMConversation *conv in listArr) {
                    if ([conv getType] == TIM_SYSTEM) {
                        continue;
                    }
                    strongSelf.unReadCount += [conv getUnReadMessageNum];
                }
            }
        }
        strongSelf.viewControllers[3].tabBarItem.badgeValue = (strongSelf.unReadCount)?[NSString stringWithFormat:@"%ld", (long)strongSelf.unReadCount]:nil;
    } fail:^(int code, NSString *msg) {
        NSLog(@"%@", msg);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
